package cn.kdlc.demo.retrofit;

import android.app.Activity;

import com.squareup.okhttp.ResponseBody;

import java.io.IOException;

import retrofit.Callback;
import retrofit.Response;
import retrofit.Retrofit;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by hetwen on 2015/12/20 0020.
 */
public class MainPresenter {

    private Activity activity;

    private DataManager manager;

    public MainPresenter() {
        manager = DataManager.getInstance();
    }

    public void bind(Activity activity) {
        this.activity = activity;
    }

    public void loadData() {
        if (manager != null) {
            manager.getState(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Response<ResponseBody> response, Retrofit retrofit) {
                    try {
                        String data = response.body().string();
                        updateView(data);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onFailure(Throwable t) {

                }
            });
        }
    }

    public void loadData2() {
        if (manager != null) {
            Observable<Response<ResponseBody>> observable = manager.getState2();
            observable
                    .subscribeOn(Schedulers.io())
                    .map(new Func1<Response<ResponseBody>, String>() {
                        @Override
                        public String call(Response<ResponseBody> response) {
                            try {
                                String data = response.body().string();
                                return data;
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            return null;
                        }
                    })
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Action1<String>() {
                        @Override
                        public void call(String s) {
                            updateView(s);
                        }
                    });
        }
    }

    public void updateView(String data) {
        if (activity != null && activity instanceof MainActivity) {
            ((MainActivity) activity).updateView(data);
        }
    }

    public void unBind() {
        activity = null;
        manager = null;
    }

}
